package org.karelun.rabbit.bridge.ui.action;

import org.eclipse.emf.common.command.Command;
import org.eclipse.jface.action.Action;
import org.eclipse.ui.IWorkbenchPart;
import org.karelun.rabbit.bridge.ITransactionEditingDomain;
import org.karelun.rabbit.bridge.ITransactionEditingDomainProvider;

public class RabbitRedoAction extends Action{
	
	private ITransactionEditingDomain domain;
	
	public RabbitRedoAction(ITransactionEditingDomain domain){
		super("Redo");
		this.domain=domain;
		update();
	}
	
	public RabbitRedoAction(){
		super("Redo");
	}
	
	public ITransactionEditingDomain getEditingDomain(){
		return domain;
	}
	
	public void setEditingDomain(ITransactionEditingDomain domain){
		this.domain=domain;
	}
	
	@Override
	public void run() {
		domain.getCommandStack().redo();
	}

	public void update() {
		setEnabled(canEnabled());
		Command redoCommand = domain.getCommandStack().getRedoCommand();
		if(redoCommand!=null&&redoCommand.getLabel()!=null){
			setText("Redo "+redoCommand.getLabel());
		}
		if(redoCommand!=null&&redoCommand.getDescription()!=null){
			setDescription("Redo "+redoCommand.getDescription());
		}
	}

	private boolean canEnabled() {
		boolean readOnly = domain.getCDOView().isReadOnly();
		boolean canRedo = domain.getCommandStack().canRedo();
		return !readOnly&&canRedo;
	}
	
	public void setActiveWorkbenchPart(IWorkbenchPart workbenchPart){
		if(workbenchPart instanceof ITransactionEditingDomainProvider){
			domain=((ITransactionEditingDomainProvider)workbenchPart).getTransactionEditingDomain();
		}
	}
}
